package com.tgu.home_action.service.utils;


import com.alibaba.fastjson.JSON;
import com.tgu.home_action.pojo.exception.IMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IMService {
    @Value("${im.sdkAppId}")
    private Long sdkAppId;
    @Value("${im.secret}")
    private String secret;
    @Value("${im.identifier}")
    private String identifier;

    private final long expire = 7200;

    @Autowired
    private HttpService httpService;

    /**
     * 获取UserSig
     */
    public String getUserSig(String userId) {
        TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(sdkAppId, secret);
        return tlsSigAPIv2.genUserSig(userId, expire);
    }

    /**
     * 导入单个账号
     */
    public void insertUser(String Identifier, String Nick, String FaceUrl) throws IMException {
        String url = getUrl("https://console.tim.qq.com/v4/im_open_login_svc/account_import");
        System.out.println(url);
        Map<String, Object> param = new HashMap<>();
        param.put("Identifier", Identifier);
        param.put("Nick", Nick);
        param.put("FaceUrl", FaceUrl);
        Map<String, Object> result = httpService.postReturnMap(url, param);
        System.out.println(result);
        if (result.get("ActionStatus").equals("FAIL")) {
            throw new IMException((String) result.get("ResultInfo"));
        }
    }

    /**
     * 查询单个账号
     */
    public Boolean accountCheck(String userId) throws IMException {
        String url = getUrl("https://console.tim.qq.com/v4/im_open_login_svc/account_check");
        System.out.println(url);
        Map<String, Object> param = new HashMap<>();
        Object[] checkItem = new Object[1];
        Map<String, String> userIdMap = new HashMap<>();
        userIdMap.put("UserID", userId);
        checkItem[0] = userIdMap;
        param.put("CheckItem", checkItem);
        Map<String, Object> result = httpService.postReturnMap(url, param);
        System.out.println(result);
        if (result.get("ActionStatus").equals("OK")) {
            List<Object> resultItems = JSON.parseArray(JSON.toJSONString(result.get("ResultItem")));
            Map<String, Object> resultItem = (Map<String, Object>) resultItems.get(0);
            return resultItem.get("AccountStatus").equals("Imported");
        } else {
            throw new IMException((String) result.get("ErrorInfo"));
        }
    }

    /**
     * 设置资料
     */
    public void setMessage(String userId, String role, Integer id) throws IMException {
        String url = getUrl("https://console.tim.qq.com/v4/profile/portrait_set");
        System.out.println(url);
        Map<String, Object> param = new HashMap<>();
        Object[] profileItem = new Object[2];
        profileItem[0] = getMessageMap("Tag_Profile_Custom_Role", role);
        profileItem[1] = getMessageMap("Tag_Profile_Custom_ID", String.valueOf(id));
        param.put("From_Account", userId);
        param.put("ProfileItem", profileItem);
        Map<String, Object> result = httpService.postReturnMap(url, param);
        System.out.println(result);
        if (result.get("ActionStatus").equals("FAIL")) {
            throw new IMException((String) result.get("ResultInfo"));
        }
    }

    /**
     * 获取信息字段
     */
    private Map<String, Object> getMessageMap(String Tag, Object Value) {
        Map<String, Object> map = new HashMap<>();
        map.put("Tag", Tag);
        map.put("Value", Value);
        return map;
    }

    /**
     * 创建群组
     */
    public String createGroup(String Name, String OwnerAccount) throws IMException {
        String url = getUrl("https://console.tim.qq.com/v4/group_open_http_svc/create_group");
        System.out.println(url);
        Map<String, Object> param = new HashMap<>();
        param.put("Owner_Account", OwnerAccount);
        param.put("Type", "ChatRoom");
        param.put("Name", Name);
        Map<String, Object> result = httpService.postReturnMap(url, param);
        System.out.println(result);
        if (result.get("ActionStatus").equals("OK")) {
            return (String) result.get("GroupId");
        } else {
            throw new IMException((String) result.get("ResultInfo"));
        }
    }

    /**
     * 解散群组
     */
    public void destroyGroup(String groupId) throws IMException {
        String url = getUrl("https://console.tim.qq.com/v4/group_open_http_svc/destroy_group");
        System.out.println(url);
        Map<String, Object> param = new HashMap<>();
        param.put("GroupId", groupId);
        Map<String, Object> result = httpService.postReturnMap(url, param);
        System.out.println(result);
        if (result.get("ActionStatus").equals("FAIL")) {
            throw new IMException((String) result.get("ResultInfo"));
        }
    }

    /**
     * 添加群成员
     */
    public void addMember(String groupId, String... userId) throws IMException {
        String url = getUrl("https://console.tim.qq.com/v4/group_open_http_svc/add_group_member");
        System.out.println(url);
        Map<String, Object> param = new HashMap<>();
        param.put("GroupId", groupId);
        Object[] memberList = new Object[userId.length];
        for (int i = 0; i < userId.length; i++) {
            Map<String, String> userMap = new HashMap<>();
            userMap.put("Member_Account", userId[i]);
            memberList[i] = userMap;
        }
        param.put("MemberList", memberList);
        Map<String, Object> result = httpService.postReturnMap(url, param);
        System.out.println(result);
        if (result.get("ActionStatus").equals("FAIL")) {
            throw new IMException((String) result.get("ResultInfo"));
        }
    }

    /**
     * 删除群成员
     */
    public void deleteMember(String groupId, String... userId) throws IMException {
        String url = getUrl("https://console.tim.qq.com/v4/group_open_http_svc/delete_group_member");
        System.out.println(url);
        Map<String, Object> param = new HashMap<>();
        param.put("GroupId", groupId);
        param.put("MemberToDel_Account", userId);
        Map<String, Object> result = httpService.postReturnMap(url, param);
        System.out.println(result);
        if (result.get("ActionStatus").equals("FAIL")) {
            throw new IMException((String) result.get("ResultInfo"));
        }
    }

    /**
     * 在群组中发送系统消息
     */
    public void sendSystemMessage(String groupId, String content) throws IMException {
        String url = getUrl("https://console.tim.qq.com/v4/group_open_http_svc/send_group_system_notification");
        System.out.println(url);
        Map<String, Object> param = new HashMap<>();
        param.put("GroupId", groupId);
        param.put("Content", content);
        Map<String, Object> result = httpService.postReturnMap(url, param);
        System.out.println(result);
        if (result.get("ActionStatus").equals("FAIL")) {
            throw new IMException((String) result.get("ResultInfo"));
        }
    }

    /**
     * 发送一条群普通文本消息
     */
    public void sendGroupMsg(String groupId, String text) throws IMException {
        String url = getUrl("https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg");
        System.out.println(url);
        Map<String, Object> param = new HashMap<>();
        param.put("GroupId", groupId);
        param.put("Random", (int) (Math.random() * 9 + 1) * 1000000);
        Object[] msgBody = new Object[1];
        msgBody[0] = getMesBody("TIMTextElem", text);
        param.put("MsgBody", msgBody);
//        System.out.println(JSON.toJSONString(param));
        Map<String, Object> result = httpService.postReturnMap(url, param);
        System.out.println(result);
        if (result.get("ActionStatus").equals("FAIL")) {
            throw new IMException((String) result.get("ResultInfo"));
        }
    }

    /**
     * 获取消息体
     */
    private Map<String, Object> getMesBody(String msgType, String text) {
        Map<String, Object> param = new HashMap<>();
        param.put("MsgType", msgType);
        Map<String, Object> data = new HashMap<>();
        data.put("Text", text);
        param.put("MsgContent", data);
        return param;
    }

    /**
     * 为url添加请求参数
     */
    private String getUrl(String url) {
        Map<String, Object> urlParam = new HashMap<>();
        urlParam.put("sdkappid", sdkAppId);
        urlParam.put("identifier", this.identifier);
        urlParam.put("usersig", getUserSig(this.identifier));
        urlParam.put("random", (int) ((Math.random() * 9 + 1) * 10000000));
        urlParam.put("contenttype", "json");
        return StringService.getUrl(url, urlParam);
    }
}
